<template>
  <el-form
    :model="addForm"
    ref="ruleAdd"
    :rules="rules"
    label-width="120px"
    class="app-container"
  >
    <el-row>
      <el-form-item label="培训名称:" prop="trainName">
        <el-input v-model="addForm.trainName" style="width: 360px" />
      </el-form-item>
      <el-form-item label="所属项目:" prop="projectId">
        <el-select style="width: 360px" v-model="addForm.projectId">
          <el-option
            v-for="item in dropDownList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            clearable
          />
        </el-select>
      </el-form-item>
    </el-row>
    <el-row>
      <el-form-item label="联系人  :" prop="contacts">
        <el-input v-model="addForm.contacts" style="width: 360px" />
      </el-form-item>
      <el-form-item label="联系方式:" prop="contactUs">
        <el-input style="width: 360px" v-model="addForm.contactUs" />
      </el-form-item>
    </el-row>
    <el-row>
      <el-form-item label="报名时间" prop="data2">
        <el-date-picker
          style="width: 360px"
          v-model="addForm.data2"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :disabledDate="disabledDate1"
        />
      </el-form-item>
      <el-form-item label="培训时间" prop="data1">
        <el-date-picker
          style="width: 360px"
          v-model="addForm.data1"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :disabledDate="disabledDate2"
        />
      </el-form-item>
    </el-row>
    <el-row>
      <el-form-item label="主办单位:" prop="organizer">
        <el-input style="width: 360px" v-model="addForm.organizer" />
      </el-form-item>
      <el-form-item label="承办单位:" prop="undertaker">
        <el-input style="width: 360px" v-model="addForm.undertaker" />
      </el-form-item>
    </el-row>
    <el-row>
      <el-form-item label="上传图片：" prop="cover">
        <ImageUpload2 v-model="addForm.cover" :limit="1" />
      </el-form-item>
    </el-row>

    <br />
    <el-row>
      <el-form-item label="报名须知：" prop="enrollNotice">
        <el-input
          style="width: 820px"
          v-model="addForm.enrollNotice"
          :rows="4"
          type="textarea"
        />
      </el-form-item>
      <br />
      <br />
    </el-row>
    <el-row justify="center">
      <el-button type="primary" @click="addFN">保 存</el-button>
      <el-button type="primary" @click="xiaFN(id, projectId)">下一步</el-button>
    </el-row>
  </el-form>
</template>

<script setup name="TrainListAdd">
import { getCurrentInstance } from "@vue/runtime-core";
import { getBaseProjectList } from "@/api/oam/basic";
import {
  trainAdd,
  trainAddList,
  trainAddUpdate,
} from "@/api/train/TrainAdd.js";
import { useRouter, useRoute } from "vue-router";
import { defineProps } from "vue";
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const dropDownList = ref([]);
const flag = ref(false);
const ruleAdd = ref(null);
const emit = defineEmits(["xiaFN"]);
const props = defineProps({
  id: "",
});
const id = ref(props.id);
const ID = ref(route.query.id);
const projectId = ref();
const data = reactive({
  form: {},
  addForm: {},
  rules: {
    trainName: [
      { required: true, message: "培训名称不能为空", trigger: "blur" },
    ],
    contacts: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
    contactUs: [
      {
        required: true,
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
    organizer: [
      { required: true, message: "主办单位不能为空", trigger: "blur" },
    ],
    undertaker: [
      { required: true, message: "承办单位不能为空", trigger: "blur" },
    ],
    enrollNotice: [
      { required: true, message: "报名须知不能为空", trigger: "blur" },
    ],
    cover: [{ required: true, message: "图片不能为空", trigger: "blur" }],
    projectId: [{ required: true, message: "请选择", trigger: "change" }],
    data1: [
      {
        required: true,
        message: "请选择一个日期",
        trigger: "change",
      },
    ],
    data2: [
      {
        required: true,
        message: "请选择一个日期",
        trigger: "change",
      },
    ],
  },
});
const { rules, addForm, form } = toRefs(data);

// 编辑数据回显
if (ID.value) {
  particulars();
}
async function particulars() {
  form.value.id = ID.value;
  let res = await trainAddList(form.value);
  addForm.value = res;
  console.log(addForm.value);
  addForm.value.pic = res?.cover;
  addForm.value.data1 = [];
  addForm.value.data2 = [];
  addForm.value.data1.push(res.trainStartTime, res.trainEndTime);
  addForm.value.data2.push(res.enrollStartTime, res.enrollEndTime);
}

// 所属项目下拉框
dropList();
function dropList() {
  getBaseProjectList().then((response) => {
    dropDownList.value = response.rows;
  });
}

// 保存按钮
function addFN() {
  return new Promise((resolve, reject) => {
    ruleAdd.value.validate((valid) => {
      if (!valid) {
        return false;
      }
      let dateTime1=addForm.value.data2[1].replace(/\-/g, "/")
        let dateTime2=addForm.value.data1[0].replace(/\-/g, "/")
        if (new Date(dateTime1).getTime() > new Date(dateTime2).getTime()) {
         return   proxy.$modal.msgError('培训时间不能早于报名时间')
        }
      if (addForm.value.id) {
        // 编辑
        addForm.value.trainStartTime = addForm.value.data1[0];
        addForm.value.trainEndTime = addForm.value.data1[1];
        addForm.value.enrollStartTime = addForm.value.data2[0];
        addForm.value.enrollEndTime = addForm.value.data2[1];
        projectId.value = addForm.value.projectId;
        trainAddUpdate(addForm.value).then((res) => {
          id.value = res.data;
          if (res.code === 200) {
            flag.value = true;
            proxy.$modal.msgSuccess("操作成功");
          } else {
            proxy.$modal.msgError("操作失败");
          }
        });
      } else {
        // 添加
        addForm.value.trainStartTime = addForm.value.data1[0];
        addForm.value.trainEndTime = addForm.value.data1[1];
        addForm.value.enrollStartTime = addForm.value.data2[0];
        addForm.value.enrollEndTime = addForm.value.data2[1];
        projectId.value = addForm.value.projectId;
        trainAdd(addForm.value).then((res) => {
          id.value = res.data;
          if (res.code === 200) {
            flag.value = true;
            proxy.$modal.msgSuccess("操作成功");
          } else {
            proxy.$modal.msgError("操作失败");
          }
        });
      }
    });
    if (flag.value) {
      resolve("成功");
    } else {
      reject("失败");
    }
  });
}

// 时间限制
// 报名日期
function disabledDate1(time) {
  // if (addForm.value.data1?.length > 0) {
  //   return time.getTime() >= new Date(addForm.value.data1[0]).getTime();
  // }
}
function disabledDate2(time) {
  if (addForm.value.data2?.length > 0) {
    let dateTime=addForm.value.data2[1].replace(/\-/g, "/")
    return time.getTime() <= new Date(dateTime).getTime();
  }
}

// <!-- 下一步 -->
async function xiaFN() {
  if (flag.value) {
    emit("xiaFN", 1, id.value, projectId.value);
  } else {
    return new Promise((resolve, reject) => {
      ruleAdd.value.validate((valid) => {
        if (!valid) {
          return false;
        }
        let dateTime1=addForm.value.data2[1].replace(/\-/g, "/")
        let dateTime2=addForm.value.data1[0].replace(/\-/g, "/")
        if (new Date(dateTime1).getTime() > new Date(dateTime2).getTime()) {
         return   proxy.$modal.msgError('培训时间不能早于报名时间')
        }
        if (addForm.value.id) {
          // 编辑
          addForm.value.trainStartTime = addForm.value.data1[0];
          addForm.value.trainEndTime = addForm.value.data1[1];
          addForm.value.enrollStartTime = addForm.value.data2[0];
          addForm.value.enrollEndTime = addForm.value.data2[1];
          projectId.value = addForm.value.projectId;
          trainAddUpdate(addForm.value).then((res) => {
            id.value = res.data;
            if (res.code === 200) {
              flag.value = true;
              emit("xiaFN", 1, id.value, projectId.value);
              proxy.$modal.msgSuccess("操作成功");
            } else {
              proxy.$modal.msgError("操作失败");
            }
          });
        } else {
          // 添加
          addForm.value.trainStartTime = addForm.value.data1[0];
          addForm.value.trainEndTime = addForm.value.data1[1];
          addForm.value.enrollStartTime = addForm.value.data2[0];
          addForm.value.enrollEndTime = addForm.value.data2[1];
          projectId.value = addForm.value.projectId;
          trainAdd(addForm.value).then((res) => {
            id.value = res.data;
            if (res.code === 200) {
              flag.value = true;
              emit("xiaFN", 1, id.value, projectId.value);
              proxy.$modal.msgSuccess("操作成功");
            } else {
              proxy.$modal.msgError("操作失败");
            }
          });
        }
      });
      if (flag.value) {
        resolve("成功");
      } else {
        reject("失败");
      }
    });
  }
}

// 返回
function goBack() {
  emit("goBack");
}
</script>

<style scope></style>
